package com.jt.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().anyRequest().permitAll();
        http.formLogin().successHandler(successHandler())
                .failureHandler(failHandler());
    }
   @Bean
    public AuthenticationSuccessHandler successHandler(){
        return (request,response,authentication)->{
            Map<String,Object> map =new HashMap();
            map.put("status", 200);
            map.put("msg", "login ok");
            writeJsonToClient(response,map);
        };
   }
   @Bean
   public AuthenticationFailureHandler failHandler(){
        return (request,response,authentication)->{
            Map<String,Object> map = new HashMap<>();
            map.put("status", 500);
            map.put("msg", "login error");
            writeJsonToClient(response,map);
        };
   }
    private void writeJsonToClient(HttpServletResponse response, Map<String, Object> map) throws IOException {
        String json = new ObjectMapper().writeValueAsString(map);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer =response.getWriter();
        writer.write(json);
        writer.flush();
    }


}
